import 'package:dio/dio.dart';
import 'package:flutter_mode/zyj/db/db.dart';
import 'package:flutter_mode/zyj/model/base_data.dart';

class DioManager {
  late Dio _dio;

  DioManager._internal() {
    _dio = new Dio(BaseOptions(
//  baseUrl: "http://test.cqsxbkj.cn/crm-xbsx/",
      baseUrl: "http://crmapp.sxbcar.com/crm-xbsx/",
      connectTimeout: Duration(seconds: 10),
      receiveTimeout: Duration(seconds: 30),
      headers: {
        //测试header
        "deviceType": "2.0",
        "deviceOS": "android",
        "deviceOSVersion": "5.1",
        "appVersion": "27",
        "deviceFactory": "OPPO",
        "deviceModel": "OPPO R9tm",
      },
    ));
    /*_dio.interceptor.request.onSend = (Options options) async {
      // 在请求被发送之前做一些事情
      await DbManager.singleton.get().then((datas) {
        if (datas != null && datas.length > 0) {
          var data = datas[0];
          if (data != null) {
            options.headers["userID"] = data["userID"];
            options.headers["token"] = data["token"];
          }
        }
      });
      return options; //continue
      // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
      // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
      //
      // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
      // 这样请求将被中止并触发异常，上层catchError会被调用。
    };
    _dio.interceptor.response.onSuccess = (Response response) {
      // 在返回响应数据之前做一些预处理
      return response; // continue
    };
    _dio.interceptor.response.onError = (DioError e) {
      // 当请求失败时做一些预处理
      return e; //continue
    };*/

    _dio.interceptors.add(InterceptorsWrapper(onRequest: (options, handler) async {
      // 在请求被发送之前做一些事情
      await DbManager.singleton.get().then((datas) {
        if (datas != null && datas.length > 0) {
          var data = datas[0];
          if (data != null) {
            options.headers["userID"] = data["userID"];
            options.headers["token"] = data["token"];
          }
        }
      });
      // return options; //continue
      // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
      // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
      //
      // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
      // 这样请求将被中止并触发异常，上层catchError会被调用。
    }, onResponse: (response, handler) {
      // 在返回响应数据之前做一些预处理
      // return response; // continue
    }, onError: (DioError e, handler) {
      // 当请求失败时做一些预处理
      // return e; //continue
    }));
  }

  static DioManager singleton = DioManager._internal();

  factory DioManager() => singleton;

  get dio {
    return _dio;
  }

  Future<ResultData> get(url, {data, options, cancelToken}) async {
    print('get请求启动! url：$url ,body: $data');
    Response response;
    try {
      response = await dio.get(
        url,
        data: data,
        options: options,
        cancelToken: cancelToken,
      );
      print('get请求成功!response.data：${response.data}');
    } on DioException catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get请求取消! ${e.message}');
      }
      print('get请求发生错误：$e');

      throw e;
    }
    ResultData result = ResultData.fromJson(response.data);
    return result;
  }

  Future<Response> getNormal(url, {data, options, cancelToken}) async {
    print('get请求启动! url：$url ,body: $data');
    Response response;
    try {
      response = await dio.get(
        url,
        data: data,
        options: options,
        cancelToken: cancelToken,
      );
      print('get请求成功!response.data：${response.data}');
    } on DioException catch (e) {
      if (CancelToken.isCancel(e)) {
        print('get请求取消! ${e.message}');
      }
      print('get请求发生错误：$e');

      throw e;
    }
    return response;
  }

  Future<ResultData> post(url, {data, options, cancelToken}) async {
    print('post请求启动! url：$url ,body: $data');
    Response response;
    try {
      response = await dio.post(
        url,
        data: data,
        options: options,
        cancelToken: cancelToken,
      );
      print('post请求成功!response.data：${response.data}');
    } on DioException catch (e) {
      if (CancelToken.isCancel(e)) {
        print('post请求取消! ${e.message}');
      }
      print('post请求发生错误：$e');

      throw e;
    }
    ResultData result = ResultData.fromJson(response.data);
    return result;
  }

  Future<Response> postNormal(url, {data, options, cancelToken}) async {
    print('post请求启动! url：$url ,body: $data');
    Response response;
    try {
      response = await dio.post(
        url,
        data: data,
        options: options,
        cancelToken: cancelToken,
      );
      print('post请求成功!response.data：${response.data}');
    } on DioException catch (e) {
      if (CancelToken.isCancel(e)) {
        print('post请求取消! ${e.message}');
      }
      print('post请求发生错误：$e');

      throw e;
    }
    return response;
  }
}
